﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace RBAC_Uthorization.Infrstructre
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
 


        private readonly EFCoreContext _context;

        public BaseRepository(EFCoreContext context)
        {
            _context = context;
        }

        //添加
        public async Task<int> AddAsync(T Entity)
        {
            await _context.AddAsync(Entity);
            return await _context.SaveChangesAsync();


        }
        //开启事务
        public async Task BeginTransactionAsync()
        {
           
           await  _context.Database.BeginTransactionAsync();
          
        }
        //提交事务
        public async Task CommitTransactionAsync()
        {
            await _context.Database.CommitTransactionAsync();
        }

        //真删除
        public async Task<int> DeleteAsync(int Id)
        {
            //var slist = _context.Set<T>().FindAsync(Id);
            //if (slist != null)
            //{
            //    //IsDel状态为可修改
            //    _context.Entry(slist).Property("del_flag").IsModified = true;
            //    //改为true 为删除
            //    _context.Entry(slist).Property("del_flag").CurrentValue = 1;
            //}
            //return await _context.SaveChangesAsync();
            var entity = await _context.Set<T>().FindAsync(Id);
            _context.Set<T>().Remove(entity);
            return await _context.SaveChangesAsync();


        }
        //根据条件查询
        public async Task<List<T>> GetAllAsunc(Expression<Func<T, bool>> expression)
        {
            return await _context.Set<T>().Where(expression).ToListAsync();
        }
        //查询全部
        public async Task<List<T>> GetAllAsync()
        {
            return await _context.Set<T>().ToListAsync();
        }
        //根据id查询
        public async Task<T> GetbyIdAsync(object Id)
        {
            return await _context.Set<T>().FindAsync(Id);
        }
        //回滚事务
        public async Task RollbackTransactionAsync()
        {
           await _context.Database.RollbackTransactionAsync();
        }

        //修改
        public async Task<int> UpdateAsync(T Entity)
        {
            _context.Update(Entity);
            return await _context.SaveChangesAsync();
        }

    }
}
